require "redis"
require "json"

module Trifle
	module Ruby
		module Queue
			class RedisConnect
				attr_accessor :config, :server

				def initialize
					@config = Config.load[::Rails.env || ENV["rack_env"] || ENV["RAILS_ENV"]]
					@server = Redis.new(url: @config["queue"]["url"])
				end

				def push(json_data)
					queue_count = self.server.rpush(self.queue, json_data)
					queue_size = self.config["queue"]["size"].to_i
					if queue_count - queue_size > 0
						arr = self.server.lrange(self.queue, 0, queue_size-1)
						self.server.ltrim(self.queue, queue_size, -1)
						clean_transactions = []
						clean_jobs = []
						clean_exceptions = []
						arr.each do |arr_json_data|
							data = JSON.parse(arr_json_data)
							case data["app_type"]
							when "transaction"
								clean_transactions << data
							when "job"
								clean_jobs << data
							when "exception"
								clean_exceptions << data
							end
						end
						ActiveSupport::Notifications.instrument("trifle_ruby.transactions", data: clean_transactions) unless clean_transactions.empty?
						ActiveSupport::Notifications.instrument("trifle_ruby.jobs", data: clean_jobs) unless clean_jobs.empty?
						ActiveSupport::Notifications.instrument("trifle_ruby.exceptions", data: clean_exceptions) unless clean_exceptions.empty?
					end
				end

				def queue
					"trifle_#{::Rails.env}_#{@config["api_key"]}:queue"
				end
			end
		end
	end
end
